package encryption;


// StringDecryptorFromBigInt.java
// Decrypt the file created by StringEncryptorToBigInt
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class StrFromBI {

	public static String decrypt(String decrypt, String pass) {

		String password = pass;

		while (password.length() < 8) {
			password += " ";
		}

		try {
			BigInteger bi = new BigInteger(decrypt);
			InputStream bin = new ByteArrayInputStream(bi.toByteArray());

			// Create a key.
			byte[] desKeyData = password.getBytes();
			DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey desKey = keyFactory.generateSecret(desKeySpec);

			// Use Data Encryption Standard cipher
			Cipher des = Cipher.getInstance("des");
			des.init(Cipher.DECRYPT_MODE, desKey);

			String decrypted_string = new String("");

			byte[] input = new byte[64];
			while (true) {
				int bytesRead = bin.read(input);
				if (bytesRead == -1)
					break;
				byte[] output = des.update(input, 0, bytesRead);
				if (output != null)
					decrypted_string = decrypted_string.concat(new String(
							output));
			}

			byte[] output = des.doFinal();
			if (output != null)
				decrypted_string = decrypted_string.concat(new String(output));
			bin.close();
			System.out.println(decrypted_string);
			return decrypted_string;
			
		} catch (InvalidKeySpecException e) {
			System.err.println(e);
		} catch (InvalidKeyException e) {
			System.err.println(e + " Key Length: " + password.length());
		} catch (NoSuchAlgorithmException e) {
			System.err.println(e);
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			System.err.println(e);
		} catch (BadPaddingException e) {
			System.err.println(e);
		} catch (IllegalBlockSizeException e) {
			System.err.println(e);
		} catch (IOException e) {
			System.err.println(e);
		}

		return "Decryption Failed";
	}
}
